<template>
  <el-form :model="formData" label-width="120px">
    <el-form-item label="名称">
      <el-input v-model="formData.name" placeholder="请输入商品名称..." />
    </el-form-item>
    <el-form-item label="副标题">
      <el-input v-model="formData.subTitle" placeholder="请输入商品副标题..." />
    </el-form-item>
    <el-form-item label="图片">
      <Tuku v-model="formData.img"></Tuku>
    </el-form-item>
    <el-form-item label="分类">
      <el-tree-select
        v-model="formData.categoryId"
        :data="data"
        :render-after-expand="false"
      />
    </el-form-item>
    <el-form-item label="价格">
      <el-input-number v-model="formData.price" :precision="2" :step="0.1" />
    </el-form-item>

    <el-form-item label="排序">
      <el-input-number v-model="formData.sort" :min="1" :max="100" />
    </el-form-item>

    <el-form-item label="详情">
      <el-input
        v-model="formData.description"
        :rows="5"
        type="textarea"
        placeholder="请输入商品描述"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import Tuku from "@/components/Tuku.vue";
import { categoryApi } from "@/api";
import { ElMessage } from "element-plus";
import { productApi } from "@/api";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
//表单数据
const formData = reactive({
  id: "",
  name: "",
  img: "",
  sort: 0,
  categoryId: "",
  price: 0,
  description: "",
  subTitle:""
});
//分类数据
const data = ref([]);

//钩子函数
onMounted(() => {
  //查询分类
  getCategoryList();
  //数据回显
  getProductInfo();
});

//提交表单
const onSubmit = () => {
  //调用接口修改商品
  updateProduct();
  //路由跳转到商品列表页面
  router.push({ name: "product-list" });
};

//查询分类列表
const getCategoryList = () => {
  categoryApi.getCategoryTree.call().then((res: any) => {
    res.forEach((item) => {
      item.value = item.id;
      item.label = item.name;
    });
    data.value = data.value.concat(res);
  });
};
//修改商品的api
const updateProduct = () => {
  productApi.update
    .call({
      id: formData.id,
      name: formData.name,
      img: formData.img,
      sort: formData.sort,
      categoryId: formData.categoryId,
      price: formData.price,
      description: formData.description,
      subTitle:""
    })
    .then((res: any) => {
      ElMessage.success("修改成功");
    });
};
//根据id查询商品信息，回显
const getProductInfo = () => {
  productApi.selectById.call({ id: route.query.id }).then((res: any) => {
    formData.id = res.id;
    formData.name = res.name;
    formData.img = res.img;
    formData.sort = res.sort;
    formData.categoryId = res.categoryId;
    formData.price = res.price;
    formData.description = res.description;
    formData.subTitle = res.subTitle;
  });
};
</script>